package com.app.studyroom.utils;

import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.provider.MediaStore;

import java.io.File;

public class FileUtils {
    public static File getFileFromUri(Context context, Uri uri) {
        try {
            String fileName = "avatar_" + System.currentTimeMillis() + ".jpg";
            File cacheFile = new File(context.getCacheDir(), fileName);
            try (Cursor cursor = context.getContentResolver().query(uri, null, null, null, null);
                 java.io.InputStream inputStream = context.getContentResolver().openInputStream(uri);
                 java.io.FileOutputStream outputStream = new java.io.FileOutputStream(cacheFile)) {

                if (inputStream == null) return null;

                byte[] buffer = new byte[4096];
                int bytesRead;
                while ((bytesRead = inputStream.read(buffer)) != -1) {
                    outputStream.write(buffer, 0, bytesRead);
                }

                return cacheFile;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}

